﻿using System;
using System.Net.Sockets;
using System.Threading;
using Roborally.CommonData.GlobaleTypes;

namespace Roborally.Netwerklaag
{
    public class handleClient
    {
        TcpClient clientSocket;
        Thread ctThread;
        int buffergrote = 64000;

        // delegate declaration
        public delegate void OntvangBericht(object sender, BinnenkomendBericht binnenkomendbericht);
        public delegate void DisconnectClient(object sender, DisconnectClientX client);

        // event declaration
        public event OntvangBericht nieuwbericht;
        public event DisconnectClient disconnectclient;

        public void startClient(TcpClient inClientSocket)
        {
            this.clientSocket = inClientSocket;
            ctThread = new Thread(listen);
            ctThread.Start();
        }

        private void listen()
        {
            byte[] bytesFrom = new byte[buffergrote];
            string dataFromClient = null;
            bool doorgaan = true;

            while (doorgaan)
            {
                try
                {
                    if (clientSocket.Connected)
                    {
                        NetworkStream networkStream = clientSocket.GetStream();
                        networkStream.Read(bytesFrom, 0, buffergrote);
                        dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                        dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                        nieuwbericht(this, new BinnenkomendBericht(dataFromClient, clientSocket));
                    }
                    else
                    {
                        throw new Exception("Connection isn't connected.");
                    }
                }
                catch (Exception ex)
                {
                    doorgaan = false;
                    disconnectclient(this, new DisconnectClientX(clientSocket));
                    doorgaan = false;
                    clientSocket.Close();
                    ctThread.Abort();
                }
            }
        }
    }
}
